import cv2
import numpy as np
from scipy.spatial import KDTree
import random

# 读取图像和模板
image = cv2.imread("image.png")
templ = cv2.imread("templ.png")
height, width, c = templ.shape

# 执行模板匹配
results = cv2.matchTemplate(image, templ, cv2.TM_CCOEFF_NORMED)

# 存储底部中心点坐标
bottom_center_points = []

# 检测匹配区域并绘制矩形框
stationNum = 0
for y in range(len(results)):
    for x in range(len(results[y])):
        if results[y][x] > 0.99:
            cv2.rectangle(image, (x, y), (x + width, y + height), (0, 255, 0), 2)
            bottom_center_x = x + width // 2
            bottom_center_y = y + height
            bottom_center_points.append((bottom_center_x, bottom_center_y))
            stationNum += 1

# 创建KD树
kdtree = KDTree(bottom_center_points)

# 生成三个随机点，并用蓝色点标出
random_points = []
for _ in range(3):
    point = (random.randint(0, image.shape[1]), random.randint(0, image.shape[0]))
    random_points.append(point)
    cv2.circle(image, point, 5, (255, 0, 0), -1)  # 使用蓝色点标出

# 连接每个随机点与其最近的底部中心点
for point in random_points:
    # 使用KD树找到最近的底部中心点
    dist, idx = kdtree.query(point)
    closest_point = bottom_center_points[idx]
    cv2.line(image, point, closest_point, (255, 0, 0), 2)  # 蓝色线连接

# 显示结果
cv2.imshow("result", image)
cv2.waitKey()
cv2.destroyAllWindows()
